const DB = require('../tools/mysql')
const uuid = require('node-uuid')

module.exports = async ctx => {

  const param = ctx.request.body
  delete param.timestamp

  if (param.id) {
    try {
      const [{ files }] = await DB('three_implementation').select('files').where('id', param.id)
      const del = await DB('three_implementation').where('id', param.id).del()
      if (del === 1) {
        param.files = files
        const [data] = await DB('three_implementation').insert(param)
        if (data === 0) {
          ctx.body = { code: 1, msg: '保存成功', data: param.id }
        } else {
          ctx.body = { code: 0, msg: '保存失败' }
        }
      } else {
        ctx.body = { code: 0, msg: '保存失败' }
      }
    } catch (e) {
      ctx.body = { code: 0, msg: '已存在此基本信息的单子，请更换或前去查看编辑' }
    }
  } else {
    param.id = uuid.v1()
    try {
      const [data] = await DB('three_implementation').insert(param)
      if (data === 0) {
        ctx.body = { code: 1, msg: '保存成功', data: param.id }
      } else {
        ctx.body = { code: 0, msg: '保存失败' }
      }
    } catch (e) {
      ctx.body = { code: 0, msg: '当天数据已存在，是否前去查看页面进行编辑' }
    }
  }

}